package org.jypj.dev.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author ZCJ
 *
 * @date 2016年4月29日上午11:36:01
 *
 * @description 短网址生成工具（调用百度短网址接口）
 */
public class DwzUtil {
	
	private static final CloseableHttpClient httpClient;
	static {
	       RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
	       httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	   }
	
	/**
	 * 生成端连接信息
	 * 
	 */
	public static String  generateShortUrl(String url) {
		try {
			HttpPost httpost = new HttpPost("http://dwz.cn/create.php");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("url", url)); // 用户名称
			httpost.setEntity(new UrlEncodedFormEntity(params,  "utf-8"));
			HttpResponse response = httpClient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			System.out.println(jsonStr);
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.getString("tinyurl"));
			return object.getString("tinyurl");
		} catch (Exception e) {
			e.printStackTrace();
			return "Error";
		}
		
	}
	
	/**
	 * 测试生成端连接
	 * @param args
	 */
	public static void main(String []args){
		generateShortUrl("http://v.youku.com/v_show/id_XMTYyMTc3MzI2NA==.html?f=27514836&from=y1.3-idx-beta-1519-23042.223465.5-1");
	}
}